/* eslint-disable @typescript-eslint/no-require-imports */
import { View, StyleSheet, Text, FlatList, Animated, Easing, RefreshControl, ActivityIndicator, Platform, TouchableOpacity, Modal, Slider } from 'react-native';

import React, { useEffect, useRef, useState, useCallback } from 'react';
import { LinearGradient } from 'expo-linear-gradient';
import { Image as ExpoImage } from 'expo-image';
import { TabView, TabBar } from 'react-native-tab-view';
import { useNavigation } from '@react-navigation/native';
import posts from '@/mock/index';

export default function TabOneScreen() {
  // console.log(posts);

  const [data, setData] = useState(posts.list);
  const [refreshing, setRefreshing] = useState(false);
  const [loadingMore, setLoadingMore] = useState(false);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [index, setIndex] = useState(0);
  const [gender, setGender] = useState('不限');
  const [ageRange, setAgeRange] = useState([18, 72]);
  const [isFilterVisible, setFilterVisible] = useState(false);

  // 创建一个Stack导航器

  const Stack = useNavigation();

  const [routes] = useState([
    { key: 'verified', title: '真人认证' },
    { key: 'recommended', title: '推荐' },
    { key: 'eastEurope', title: '东欧' },
    { key: 'europeAmerica', title: '欧美' },
    { key: 'japanKorea', title: '日韩' },
    { key: 'southeastAsia', title: '东南亚' },
    { key: 'chinaRegion', title: '中港台' },
    { key: 'others', title: '其他' },
  ]);

  // 刷新
  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    try {
      // 这里执行你的数据刷新逻辑
      console.log("刷新");
    } catch (error) {
      console.error("刷新失败:", error);
    } finally {
      // 添加延迟以确保刷新动画完整显示
      setTimeout(() => setRefreshing(false), Platform.OS === "ios" ? 500 : 300);
    }
  }, []);

  // 加载更多
  const loadMore = useCallback(async () => {
    if (loadingMore || !hasMore) return;

    setLoadingMore(true);
    try {
      await new Promise((resolve) => setTimeout(resolve, 1000));

      setLoadingMore(false);
      console.log("加载更多");

      // if (page >= 5) {
      //   setHasMore(false);
      // }
    } finally {
      setLoadingMore(false);
    }
  }, [page, hasMore]);

  const onEndReached = () => {
    if (!refreshing && !loadingMore && hasMore) {
      loadMore();
    }
  };

  const animatedValues = useRef(
    data.map(() => ({
      scale: new Animated.Value(0),
      translateY: new Animated.Value(50),
      opacity: new Animated.Value(0),
    })),
  ).current;

  const animateItem = (index: number) => {
    const delay = (index % 3) * 100; // 每行的卡片错开显示

    Animated.parallel([
      Animated.spring(animatedValues[index].scale, {
        toValue: 1,
        tension: 50,
        friction: 7,
        useNativeDriver: true,
      }),

      Animated.timing(animatedValues[index].translateY, {
        toValue: isMiddleElement(index) ? 60 : 0,
        duration: 800,
        delay,
        useNativeDriver: true,
        easing: Easing.bezier(0.25, 0.1, 0.25, 1),
      }),
      Animated.timing(animatedValues[index].opacity, {
        toValue: 1,
        duration: 600,
        delay,
        useNativeDriver: true,
      }),
    ]).start();
  };

  const resetAnimation = (index: number) => {
    animatedValues[index].scale.setValue(0);
    animatedValues[index].translateY.setValue(50);
    animatedValues[index].opacity.setValue(0);
  };

  const onViewableItemsChanged = ({ changed }) => {
    changed.forEach((item) => {
      if (item.isViewable) {
        animateItem(item.index);
      } else {
        resetAnimation(item.index);
      }
    });
  };

  const viewabilityConfig = {
    itemVisiblePercentThreshold: 10, // 当元素 10% 进入视口时触发
  };

  const viewabilityConfigCallbackPairs = useRef([
    { onViewableItemsChanged, viewabilityConfig },
  ]);

  const isMiddleElement = (index: number) => {
    return index % 3 === 1; // 每行3个元素，索引为1的是中间元素
  };

  // 筛选用户
  const filteredData = data.filter(item => {
    const isGenderMatch = gender === '不限' || item.gender === gender;
    const isAgeMatch = item.age >= ageRange[0] && item.age <= ageRange[1];
    return isGenderMatch && isAgeMatch;
  });

  // 显示筛选模态框
  const toggleFilter = () => {
    setFilterVisible(!isFilterVisible);
  };

  // 渲染筛选模态框
  const renderFilterModal = () => (
    <Modal
      visible={isFilterVisible}
      transparent={true}
      animationType="slide"
    >
      <View style={styles.modalContainer}>
        <View style={styles.modalContent}>
          <Text>筛选</Text>
          <Text>性别</Text>
          <View style={styles.genderOptions}>
            <TouchableOpacity onPress={() => setGender('不限')}>
              <Text>不限</Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={() => setGender('男')}>
              <Text>男</Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={() => setGender('女')}>
              <Text>女</Text>
            </TouchableOpacity>
          </View>
          <Text>年龄</Text>
          
          <Text>{ageRange[0]} - {ageRange[1]}</Text>
          <TouchableOpacity onPress={toggleFilter}>
            <Text>确认</Text>
          </TouchableOpacity>
        </View>
      </View>
    </Modal>
  );

  // 渲染列表
  const renderFlatList = useCallback((data: any) => {

    
    return (
      <FlatList<any>
        key={data.filter((item: any) => item.type === 'recommended')}
        data={data.filter((item: any) => item.type === 'recommended')}
        numColumns={3}
        renderItem={({ item, index }) => (

          <Animated.View
            key={item.id}
            style={[
              styles.userCard,
              {
                opacity: animatedValues[index].opacity,
                transform: [
                  { scale: animatedValues[index].scale },
                  { translateY: animatedValues[index].translateY },
                ],
              },
            ]}

          >
            <TouchableOpacity onPress={() =>
              Stack.navigate('details', { id: '1' })
              // router.push('/index/details')
            }>
              <View style={styles.avatarContainer}>
                <ExpoImage
                  source={item.avatar}
                  style={styles.avatar}
                  cachePolicy='disk'
                  contentFit="cover"
                  transition={200}
                  placeholder={placeholderImage}
                  placeholderContentFit="cover"
                />
                <View style={styles.onlineIndicator} />
                <View style={styles.verifiedBadge}>
                  <ExpoImage cachePolicy='disk' transition={200} placeholder={placeholderImage} source={require('../../assets/images/实名认证.png')} style={styles.verifiedBadgeImage} />
                </View>
              </View>
              <View style={styles.userInfo}>
                <Text style={styles.userName}>{item.name}</Text>
                <Text style={styles.flag}>{item.flag}</Text>
              </View>
            </TouchableOpacity>
          </Animated.View>
        )}
        keyExtractor={(item) => item.id.toString()}
        showsVerticalScrollIndicator={false}
        contentContainerStyle={styles.grid}
        columnWrapperStyle={styles.row}
        viewabilityConfigCallbackPairs={viewabilityConfigCallbackPairs.current}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            colors={['#0000ff']}
            tintColor="#0000ff"
            progressBackgroundColor="#ffffff"
            progressViewOffset={Platform.select({
              ios: 50,
              android: 0,
            })}
            title={Platform.select({
              ios: '正在刷新...',
              android: '下拉刷新',
            })}
            titleColor="#0000ff"
            enabled={Platform.OS !== 'web'} // 在 Web 端禁用
          />
        }
        onEndReached={onEndReached}
        onEndReachedThreshold={0.1}
        ListFooterComponent={
          loadingMore ? (
            <View style={styles.loadingMore}>
              <ActivityIndicator size="small" color="#0000ff" />
            </View>
          ) : !hasMore ? (
            <Text style={styles.noMoreText}>没有更多数据了</Text>
          ) : null
        }
        initialNumToRender={10}
        maxToRenderPerBatch={10}
        windowSize={5}
        removeClippedSubviews={true}
      />
    )
  }, [index])


  //占位图片
  const placeholderImage = require('@/assets/images/图片占位1.png');

  const renderScene = ({ route }) => {
    switch (route.key) {
      case 'verified':
        return <View style={{ flex: 1, backgroundColor: '' }}>
          <LinearGradient
            colors={['rgba(173,216,230,1)', 'rgba(173,216,230,0)']}
            style={[styles.backgroundGradient, { height: '40%' }]}
          />
          {renderFlatList(filteredData)}
        </View>;
      case 'recommended':
        return <View style={{ flex: 1, backgroundColor: '' }}>
          <LinearGradient
            colors={['rgba(173,216,230,1)', 'rgba(173,216,230,0)']}
            style={[styles.backgroundGradient, { height: '40%' }]}
          />
          {renderFlatList(filteredData)}
        </View>;
      case 'barber':
        return <View style={{ flex: 1, backgroundColor: '' }}>
          <LinearGradient
            colors={['rgba(173,216,230,1)', 'rgba(173,216,230,0)']}
            style={[styles.backgroundGradient, { height: '40%' }]}
          />
          {renderFlatList(data.filter(item => item.type === 'barber'))}
        </View>;
      case 'europeAmerica':
        return <View style={{ flex: 1, backgroundColor: '' }}>
          <LinearGradient
            colors={['rgba(173,216,230,1)', 'rgba(173,216,230,0)']}
            style={[styles.backgroundGradient, { height: '40%' }]}
          />
          {renderFlatList(filteredData)}
        </View>;
      case 'eastEurope':
        return <View style={{ flex: 1, backgroundColor: '' }}>
          <LinearGradient
            colors={['rgba(173,216,230,1)', 'rgba(173,216,230,0)']}
            style={[styles.backgroundGradient, { height: '40%' }]}
          />
          {renderFlatList(filteredData)}
        </View>;
      case 'japanKorea':
        return <View style={{ flex: 1, backgroundColor: '' }}>
          <LinearGradient
            colors={['rgba(173,216,230,1)', 'rgba(173,216,230,0)']}
            style={[styles.backgroundGradient, { height: '40%' }]}
          />
          {renderFlatList(filteredData)}
        </View>;
      case 'southeastAsia':
        return <View style={{ flex: 1, backgroundColor: '' }}>
          <LinearGradient
            colors={['rgba(173,216,230,1)', 'rgba(173,216,230,0)']}
            style={[styles.backgroundGradient, { height: '40%' }]}
          />
          {renderFlatList(filteredData)}
        </View>;
      case 'chinaRegion':
        return <View style={{ flex: 1, backgroundColor: '' }}>
          <LinearGradient
            colors={['rgba(173,216,230,1)', 'rgba(173,216,230,0)']}
            style={[styles.backgroundGradient, { height: '40%' }]}
          />
          {renderFlatList(filteredData)}
        </View>;
      case 'others':
        return <View style={{ flex: 1, backgroundColor: '' }}>
          <LinearGradient
            colors={['rgba(173,216,230,1)', 'rgba(173,216,230,0)']}
            style={[styles.backgroundGradient, { height: '40%' }]}
          />
          {renderFlatList(filteredData)}
        </View>;
      default:
        return null;
    }
  };


  const renderTabBar = (props) => (
    <View style={styles.TabBarFlex}>
      <TabBar
        {...props}
        inactiveColor='#000'
        activeColor='#000'
        
        scrollEnabled
        style={{
          width: '70%',
          overflow: 'hidden',
          backgroundColor: '#fff',
          elevation: 0, // Android阴影
          shadowColor: 'transparent', // iOS阴影
          shadowOffset: { width: 0, height: 0 },
          shadowOpacity: 0,
          shadowRadius: 0
        }}
        indicatorStyle={{
          backgroundColor: '#00b0f0',
        }}
      />
      <TouchableOpacity
        style={styles.filterButton}
        onPress={toggleFilter}
      >
        <ExpoImage
          source={require('@/assets/images/菜单.png')}
          style={styles.filterIcon}
        />
      </TouchableOpacity>
    </View>
  );




  return (
    <>
      {renderFilterModal()}
      <TabView
        navigationState={{ index, routes }}
        renderScene={renderScene}
        onIndexChange={setIndex}
        renderTabBar={renderTabBar}
        style={styles.container}
        lazy
        lazyPreloadDistance={1}
        onSwipeStart={() => console.log('Swipe started')}
      />
    </>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#f0f8ff",
    overflow: 'hidden', // 防止内容溢出
  },
  grid: {
    paddingHorizontal: 5,
    paddingTop: 20, // 添加顶部padding
  },
  userCard: {
    width: "31%",
    alignItems: "center",
    marginBottom: 35,
    marginHorizontal: "1.5%",
    marginTop: 20,
  },
  avatarContainer: {
    position: "relative",
    marginBottom: 8,
  },
  avatar: {
    width: 120,
    height: 120,
    borderRadius: 60,
    backgroundColor: "#f0f0f0",
  },
  onlineIndicator: {
    position: "absolute",
    right: 8,
    bottom: 8,
    width: 15,
    height: 15,
    borderRadius: 8,
    backgroundColor: "#4CAF50",
    borderWidth: 2,
    borderColor: "white",
  },
  verifiedBadge: {
    position: "absolute",
    right: 10,
    top: 0,
    borderRadius: 12,
    width: 20,
    height: 20,
  },
  userInfo: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: 'center', // 垂直居中
    marginTop: 5,
  },
  userName: {
    fontSize: 16,
    marginRight: 5,
  },
  flag: {
    fontSize: 18,
  },
  row: {
    justifyContent: "flex-start",
    paddingHorizontal: 5,
  },
  verifiedBadgeImage: {
    width: 20,
    height: 20,
  },
  stickyHeader: {
    position: "absolute",
    top: 0,
    left: 0,
    right: 0,
    height: 60,
    zIndex: 100,
    paddingTop: 10,
  },
  headerContent: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  headerTitle: {
    fontSize: 20,
    fontWeight: "bold",
  },
  backgroundGradient: {
    position: "absolute",
    top: 0,
    left: 0,
    right: 0,
    height: "40%",
    zIndex: -1,
  },
  loadingMore: {
    padding: 10,
    justifyContent: "center",
    alignItems: "center",
  },
  noMoreText: {
    textAlign: "center",
    padding: 10,
    color: "#666",
  },
  TabBarFlex: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    backgroundColor: '#fff',
  },
  filterButton: {
    padding: 10,
    marginRight: 15,
  },
  filterIcon: {
    width: 20,
    height: 20,
  },
  modalContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
  },
  modalContent: {
    width: '80%',
    backgroundColor: 'white',
    padding: 20,
    borderRadius: 10,
  },
  genderOptions: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginVertical: 10,
  },
});




